/**
 * 
 */
package com.ms.service.module.account;

import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ms.game.db.dto.DataTransfer;
import com.ms.service.module.account.db.AccountDAO;
import com.ms.service.module.account.db.AccountModel;
import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.service.module.task.TaskAsyncCommand;

/**
 * 帳號斷線後如果是立即玩帳號就把帳號 id 放回可用的帳號 id 清單中
 * 
 * @author TW15010
 * @see com.ms.service.module.account.AccountModule#unusedTrialAccountList
 */
public class ReleaseTrialAccountIdAsync extends TaskAsyncCommand {
	
	/** log4j object */
	private static final Log log = LogFactory.getLog(ReleaseTrialAccountIdAsync.class);
	
	/** account id 對應的帳號是立即玩帳號 */
	private static final int RES_IS_TRIAL_ACCOUNT = 1;

	/** 傳入參數不正確 */
	private static final int RES_INVALID_PARAM = 2;

	/** 從 db 載入資料失敗 */
	private static final int RES_LOAD_DATA_FAIL = 3;

	private AccountModule accountModule = null;

	private GUID accountId = null;

	private int result = 0;

	public ReleaseTrialAccountIdAsync(AccountModule accountModule, GUID accountId) {
		this.accountModule = accountModule;
		this.accountId = accountId;
	}

	@Override
	public void asyncExecute() throws Exception {
		if (accountId == null) {
			result = RES_INVALID_PARAM;
			return;
		}

		AccountModel model = AccountDAO.loadAccountModelByAccountId(accountId);
		if (model == null) {
			result = RES_LOAD_DATA_FAIL;
			return;
		}

		Account account = DataTransfer.transfer(model);
		if (account.isTrialAccount()) {
			result = RES_IS_TRIAL_ACCOUNT;
			return;
		}
	}

	@Override
	public void execute() throws Exception {
		// 確認帳號是立即玩帳號
		if (result != RES_IS_TRIAL_ACCOUNT) {
			return;
		}

		if (accountModule == null) {
			return;
		}

		// 把立即玩帳號的 account id 加回可用清單中
		ConcurrentLinkedQueue<GUID> unUsedTrialAccountList = accountModule.getUnusedTrialAccountList();
		if(unUsedTrialAccountList != null){
			if(!unUsedTrialAccountList.contains(accountId)){
				unUsedTrialAccountList.add(accountId);	
			}
			else{
				//有可能是體驗帳號回復機制在異步處理過程中已經先回復了
				if(log.isInfoEnabled()){
					log.info(accountId.toString()+" may restored by other way");
				}
			}
		}
		
		if (log.isInfoEnabled()) {
			log.info(accountModule.getModuleName() + " trial account " + accountId.toString() + " released. ("
					+ accountModule.getUnusedTrialAccountList().size() + "/" + accountModule.getOwnTrialAccountId().size() + ")");
		}
	}
}
